<!DOCTYPE html>
<html lang="zh-cn">
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <title>简易实现 WordPress 自动本地化文章中的外部图片 - Feng&#39;s Blog - 大灰鼠的博客</title>
  <meta name="renderer" content="webkit" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>

<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />

<meta name="theme-color" content="#f8f5ec" />
<meta name="msapplication-navbutton-color" content="#f8f5ec">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="#f8f5ec">


<meta name="author" content="Feng" /><meta name="description" content="我一直坚持可以不用插件实现的功能尽量不用插件，即使有些插件功能强大，定制很度高。因为很多功能自己更本很少用得上或者是更本用不到。越来越多插件" /><meta name="keywords" content="feng, 折腾人生, 电脑维修, 手机玩转, 技术心得, 拆机, 网站建设, 快乐悠悠, uu, 悠悠, 博客" />






<meta name="generator" content="Hugo 0.76.5 with theme even" />


<link rel="canonical" href="https://uu126.gitee.io/2015/202.html" />
<link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png">
<link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<link rel="mask-icon" href="/safari-pinned-tab.svg" color="#5bbad5">



<link href="/sass/main.min.c7bc1becf36bcf6a9ebd25d2947e43a2eb745ddb0c9a32b43126fd7fa460c351.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3.1.20/dist/jquery.fancybox.min.css" integrity="sha256-7TyXnr2YU040zfSP+rEcz29ggW4j56/ujTPwjMzyqFY=" crossorigin="anonymous">


<meta property="og:title" content="简易实现 WordPress 自动本地化文章中的外部图片" />
<meta property="og:description" content="我一直坚持可以不用插件实现的功能尽量不用插件，即使有些插件功能强大，定制很度高。因为很多功能自己更本很少用得上或者是更本用不到。越来越多插件" />
<meta property="og:type" content="article" />
<meta property="og:url" content="https://uu126.gitee.io/2015/202.html" />
<meta property="article:published_time" content="2015-03-03T11:02:54+00:00" />
<meta property="article:modified_time" content="2015-03-03T11:02:54+00:00" />
<meta itemprop="name" content="简易实现 WordPress 自动本地化文章中的外部图片">
<meta itemprop="description" content="我一直坚持可以不用插件实现的功能尽量不用插件，即使有些插件功能强大，定制很度高。因为很多功能自己更本很少用得上或者是更本用不到。越来越多插件">
<meta itemprop="datePublished" content="2015-03-03T11:02:54+00:00" />
<meta itemprop="dateModified" content="2015-03-03T11:02:54+00:00" />
<meta itemprop="wordCount" content="1809">



<meta itemprop="keywords" content="" />
<meta name="twitter:card" content="summary"/>
<meta name="twitter:title" content="简易实现 WordPress 自动本地化文章中的外部图片"/>
<meta name="twitter:description" content="我一直坚持可以不用插件实现的功能尽量不用插件，即使有些插件功能强大，定制很度高。因为很多功能自己更本很少用得上或者是更本用不到。越来越多插件"/>

<!--[if lte IE 9]>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/classlist/1.1.20170427/classList.min.js"></script>
<![endif]-->

<!--[if lt IE 9]>
  <script src="https://cdn.jsdelivr.net/npm/html5shiv@3.7.3/dist/html5shiv.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/respond.js@1.4.2/dest/respond.min.js"></script>
<![endif]-->

</head>
<body>
  <div id="mobile-navbar" class="mobile-navbar">
  <div class="mobile-header-logo">
    <a href="/" class="logo">Feng&#39;s Blog</a>
  </div>
  <div class="mobile-navbar-icon">
    <span></span>
    <span></span>
    <span></span>
  </div>
</div>
<nav id="mobile-menu" class="mobile-menu slideout-menu">
  <ul class="mobile-menu-list">
    <a href="/">
        <li class="mobile-menu-item">Home</li>
      </a><a href="/post/">
        <li class="mobile-menu-item">Archives</li>
      </a><a href="/tags/">
        <li class="mobile-menu-item">Tags</li>
      </a><a href="/links/">
        <li class="mobile-menu-item">Links</li>
      </a><a href="/ly/">
        <li class="mobile-menu-item">Ly</li>
      </a><a href="/about/">
        <li class="mobile-menu-item">About</li>
      </a>
  </ul>
</nav>
  <div class="container" id="mobile-panel">
    <header id="header" class="header">
        <div class="logo-wrapper">
  <a href="/" class="logo">Feng&#39;s Blog</a>
</div>

<nav class="site-navbar">
  <ul id="menu" class="menu">
    <li class="menu-item">
        <a class="menu-item-link" href="/">Home</a>
      </li><li class="menu-item">
        <a class="menu-item-link" href="/post/">Archives</a>
      </li><li class="menu-item">
        <a class="menu-item-link" href="/tags/">Tags</a>
      </li><li class="menu-item">
        <a class="menu-item-link" href="/links/">Links</a>
      </li><li class="menu-item">
        <a class="menu-item-link" href="/ly/">Ly</a>
      </li><li class="menu-item">
        <a class="menu-item-link" href="/about/">About</a>
      </li>
  </ul>
</nav>
    </header>

    <main id="main" class="main">
      <div class="content-wrapper">
        <div id="content" class="content">
          <article class="post">
    
    <header class="post-header">
      <h1 class="post-title">简易实现 WordPress 自动本地化文章中的外部图片</h1>

      <div class="post-meta">
        <span class="post-time"> 2015-03-03 </span>
        <div class="post-category">
            <a href="/categories/it%E7%BB%BC%E5%90%88%E6%8A%80%E6%9C%AF/"> IT综合技术 </a>
            </div>
          <span class="more-meta"> 约 1809 字 </span>
          <span class="more-meta"> 预计阅读 4 分钟 </span>
        
      </div>
    </header>

    <div class="post-toc" id="post-toc">
  <h2 class="post-toc-title">文章目录</h2>
  <div class="post-toc-content always-active">
    <nav id="TableOfContents">
  <ul>
    <li>
      <ul>
        <li>
          <ul>
            <li><a href="#代码如下">代码如下：</a></li>
          </ul>
        </li>
      </ul>
    </li>
  </ul>
</nav>
  </div>
</div>
    <div class="post-content">
      <p>我一直坚持可以不用插件实现的功能尽量不用插件，即使有些插件功能强大，定制很度高。因为很多功能自己更本很少用得上或者是更本用不到。越来越多插件反而让网站越来越复杂沉重，甚至会拖慢你的网站。<br>
写博客一段时间常常会用到一些网络上的资源，最经常的当然要数图片了，直接引用虽然很简单但是很不可控，因为大多数网站做维护开启了防盗链或者把图片删除了的话我这边的话会有好多404图片。所以我会把图片上传到自己的网站上，每次写文章需要引用的图片很多的话会比较很费力。于是我自己写了一段代码，在文章保存的时候自动将图片本地化，用了几天感觉不错。在这里分享出来，功能比较的简单，我会持续完善这个功能。</p>
<h3 id="代码如下">代码如下：</h3>
<pre class="lang:php decode:true " >/************自动下载外部图片开始**************/
function save_post_fix($content){
        global $wpdb;
    $post_id = get_the_ID();
    $upload_dir = wp_upload_dir();
    $path = $upload_dir[“url”];
    $realPath = $upload_dir[“path”];
    $pathbase = $upload_dir[“baseurl”].’/’;
    if(!is_dir($realPath)){
        mkdirs($realPath);
    }
    $pagelink=array();
    $pattern_page = ‘/&lt;img([sS]*?)src=\[“|’](.*?)\[“|’]([sS]*?)&gt;/i’;
    preg_match_all($pattern_page, $content, $pagelink[]);
    foreach ($pagelink[0][2] as $key =&gt; $value) {
        $pic_url = $value;
        $url_feter = parse_url($pic_url);
        if(stripos($url_feter[“host”],“zhnytech.com”)){   //此处修改成自己的网址
            continue;
        }else{
                 $ch = curl_init();
             curl_setopt($ch,CURLOPT_HEADER,1);
             curl_setopt($ch, CURLOPT_NOBODY, TRUE);
             curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
             curl_setopt($ch,CURLOPT_URL,$pic_url);
             $hd = curl_exec($ch);
             if(!emptyempty($hd) && !(stripos($hd,’Content-Length: image/png’)||stripos($hd,’Content-Length: image/jpg’))){
                $fp =file_get_contents($pic_url);
                $pic_name =basename($url_feter[“path”]);
                $savePath = $realPath.’/’.$pic_name;
                $fullPath = $path.’/’.$pic_name;
                if(file_exists($savePath)){
                    $savePath = $realPath.’/’.str_replace(‘.’,’_’.date(“YmdHis”).‘.’ ,$pic_name);
                    $fullPath = $path.’/’.str_replace(‘.’,’_’.date(“YmdHis”).‘.’ ,$pic_name);
                }
                if(file_put_contents($savePath,$fp)){
                    $content = str_replace($pic_url, $fullPath, $content);
                    $pic_xiangdui = str_replace($pathbase,”,$fullPath);
                    $wpdb-&gt;query(“INSERT INTO zblo1Agd_postmeta (post_id, meta_key, meta_value)  VALUES (‘{$post_id}’, ‘_wp_attached_file’ ,'{$pic_xiangdui}’)”);  //此处需修改成自己的数据库前缀
                    $picSize = getimagesize(‘$fullPath‘);
                    $picInfo =array();
                    $picInfo[‘file’] = $pic_xiangdui;
                    $picInfo[‘width’] = $picSize[0];
                    $picInfo[‘height’] = $picSize[1];
                    $picInfo[‘sizes’] = array();
                    $picInfo[‘image_meta’] = array(
                          ‘aperture’ =&gt; ‘0’,
                          ‘credit’   =&gt; ”,
                          ‘camera’   =&gt;”,
                          ‘caption’  =&gt;”,
                          ‘created_timestamp’ =&gt;’0′,
                          ‘copyright’ =&gt;’0′,
                          ‘focal_length’ =&gt;’0′,
                          ‘iso’         =&gt;’0′,
                          ‘shutter_speed’  =&gt;’0′,
                          ‘title’   =&gt; ”
                        );
                    $picStr = serialize($picInfo);
                    $wpdb-&gt;query(“INSERT INTO zblo1Agd_postmeta (post_id, meta_key, meta_value)  VALUES (‘{$post_id}’, ‘_wp_attachment_metadata’ ,'{$picStr}’)”);  //此处需修改成自己的数据库前缀
                    $daytime= date(“Y-m-d H:i:s”);
                    $daytimegmt =date(“Y-m-d H:i:s”,strtotime(‘-8 hours’));
                    list($pictitle)=explode(‘.’,$pic_name);
                    $wpdb-&gt;query(“
                            INSERT INTO zblo1Agd_posts (post_author, post_date, post_date_gmt,post_content,post_title,post_excerpt,
                            post_status,comment_status,ping_status,post_password,post_name,to_ping,pinged,post_modified,post_modified_gmt,
                            post_content_filtered,post_parent,guid,menu_order,post_type,post_mime_type,comment_count)  VALUES (
                            ‘1’,'{$daytime}’,'{$daytimegmt}’,”,'{$pictitle}’,”,’inherit’,’open’,’open’,”,'{$pictitle}’,”,”,
                            ‘{$daytime}’,'{$daytimegmt}’,”,’0′,'{$fullPath}’,’0′,’attachment’,'”.$picSize[‘mime’].“‘,’0’)”);  //此处需修改成自己的数据库前缀
                }
            }
        }
    }
    return $content;
}
add_filter( ‘content_save_pre’, ‘save_post_fix’);
/************自动下载外部图片结束**************/</pre><blockquote>
</blockquote>

    </div>

    <div class="post-copyright">
  <p class="copyright-item">
    <span class="item-title">文章作者</span>
    <span class="item-content">Feng</span>
  </p>
  <p class="copyright-item">
    <span class="item-title">上次更新</span>
    <span class="item-content">
        2015-03-03
        
    </span>
  </p>
  
  
</div>
<div class="post-reward">
  <input type="checkbox" name="reward" id="reward" hidden />
  <label class="reward-button" for="reward">赞赏支持</label>
  <div class="qr-code">
    
    <label class="qr-code-image" for="reward">
        <img class="image" src="https://cdn.uu126.cn/hugo/wechat.png">
        <span>微信打赏</span>
      </label>
    <label class="qr-code-image" for="reward">
        <img class="image" src="https://cdn.uu126.cn/hugo/alipay.png">
        <span>支付宝打赏</span>
      </label>
  </div>
</div><footer class="post-footer">
      
      <nav class="post-nav">
        <a class="prev" href="/2015/203.html">
            <i class="iconfont icon-left"></i>
            <span class="prev-text nav-default">元宵节……</span>
            <span class="prev-text nav-mobile">上一篇</span>
          </a>
        <a class="next" href="/2015/201.html">
            <span class="next-text nav-default">Win8.1与Win7系统之间如何实现文件共享（Win10可用）</span>
            <span class="next-text nav-mobile">下一篇</span>
            <i class="iconfont icon-right"></i>
          </a>
      </nav>
    </footer>
  </article>
        </div>
        

  
  <div id="vcomments"></div>
  <script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
  <script src='//unpkg.com/valine/dist/Valine.min.js'></script>
  <script type="text/javascript">
    new Valine({
        el: '#vcomments' ,
        appId: '5sMkTX4FLjetFnfbOhaDTCDJ-9Nh9j0Va',
        appKey: '25KXCqIqAN142RQn4fBrsI87',
        notify:  false ,
        verify:  false ,
        avatar:'mm',
        placeholder: '说点什么吧...',
        visitor:  false 
    });
  </script>

  

      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="social-links">
  <a href="https://uu126.gitee.io/index.xml" type="application/rss+xml" class="iconfont icon-rss" title="rss"></a>
</div>

<div class="copyright">
  <span class="copyright-year">  
  Hosted by <a href="https://pages.coding.me" style="font-weight: bold">Coding Pages</a> + <a href="https://cloud.tencent.com/redirect.php?redirect=1005&cps_key=4e78216aea817227ff0c96d93a00fd4b" target="_blank" rel="nofollow">腾讯云 + </a><a href="https://console.upyun.com/register/?invite=S1JeTquHL" target="_blank" rel="nofollow"><span class="with-love"><img src="https://cdn.lancn.cn/images/upyun.png" style="width:45px;vertical-align:middle;" alt="又拍云存储"></span></a>
   </span> 
  <div class="busuanzi-footer">
    <a target="_blank"  href="http://www.beian.miit.gov.cn">浙ICP备11026647号-3</a><span class="post-meta-divider"> | </span><a target="_blank" href="http://www.beian.gov.cn/portal/registerSystemInfo?recordcode=33088102001325"><span class="with-love"><img src="https://cdn.uu126.cn/icon-police.png" style="width:14px;"></span> 浙公网安备33088102001325号</a>
  </div>
  <span class="power-by">
    由 <a class="hexo-link" href="https://gohugo.io">Hugo</a> 强力驱动
  </span>
  <span class="division">|</span>
  <span class="theme-info">
    主题 - 
    <a class="theme-link" href="https://github.com/olOwOlo/hugo-theme-even">Even</a>
  </span>
   

  

  <span class="copyright-year">
    &copy; 
    2012 - 
    2020<span class="heart"><i class="iconfont icon-heart"></i></span><span>Feng</span>
  </span>
</div>

    </footer>

    <div class="back-to-top" id="back-to-top">
      <i class="iconfont icon-up"></i>
    </div>
  </div>
  <script src="/lib/highlight/highlight.pack.js?v=20171001"></script>
  <script src="https://cdn.jsdelivr.net/npm/jquery@3.2.1/dist/jquery.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
  <script src="https://cdn.jsdelivr.net/npm/slideout@1.0.1/dist/slideout.min.js" integrity="sha256-t+zJ/g8/KXIJMjSVQdnibt4dlaDxc9zXr/9oNPeWqdg=" crossorigin="anonymous"></script>
  <script src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3.1.20/dist/jquery.fancybox.min.js" integrity="sha256-XVLffZaxoWfGUEbdzuLi7pwaUJv1cecsQJQqGLe7axY=" crossorigin="anonymous"></script>



<script type="text/javascript" src="/js/main.min.c12618f9a600c40bd024996677e951e64d3487006775aeb22e200c990006c5c7.js"></script>








</body>
</html>
